import type { Word } from '@/typings'
import { wordListFetcher } from '@/utils/wordListFetcher'
import { Button, Row, Select } from 'antd'
import { useMemo, useState } from 'react'
import useSWR from 'swr'

export function WordInputer() {
  const [options, setOptions] = useState<Array<{ value: string; label: string }>>([])

  const { data: wordList, error, isLoading } = useSWR('/dicts/2025KaoYanHongBaoShu.json', wordListFetcher)

  const map = useMemo(() => {
    const tempMap = new Map<string, Word>()
    wordList?.forEach((word) => {
      tempMap.set(word.name, word)
    })
    return tempMap
  }, [wordList]) // 依赖于 wordList

  const allWords = useMemo(() => {
    return Array.from(map.keys())
  }, [map]) // 依赖于 map

  const cacheStr = localStorage.getItem('cacheWords')
  const cacheWords = cacheStr ? JSON.parse(cacheStr) : []

  const [defaultOptions, setDefaultOptions] = useState<Array<{ value: string; label: string }>>([])
  useMemo(() => {
    const cacheStr = localStorage.getItem('cacheWords')
    const cacheWords = cacheStr ? JSON.parse(cacheStr) : []
    let defaultOptions: Array<{ value: string; label: string }> = []
    if (map.size > 0) {
      defaultOptions = cacheWords.map((word: string) => {
        const w: Word = map.get(word) as Word
        return { value: word, label: `${word} ${w.trans[0]}` }
      })
    } else {
      defaultOptions = []
    }
    setDefaultOptions(defaultOptions)
    return defaultOptions
  }, [map])

  const handleClick = () => {
    console.log('click')
    // 创建要保存的内容
    const data = localStorage.getItem('cacheWords') + ''
    const blob = new Blob([data], { type: 'text/plain' }) // 创建 Blob 对象
    const url = URL.createObjectURL(blob) // 创建 URL

    // 创建一个链接元素
    const a = document.createElement('a')
    a.href = url
    a.download = 'example.txt' // 指定下载的文件名

    // 触发点击事件以下载文件
    document.body.appendChild(a)
    a.click()

    // 清理
    document.body.removeChild(a)
    URL.revokeObjectURL(url) // 释放 URL 对象
  }

  return (
    <Row style={{ backgroundColor: 'white', height: '100vh' }} className="flex items-center justify-center">
      {!isLoading && (
        <Select
          mode="multiple"
          className="w-full"
          filterOption={false}
          options={options}
          showSearch={true}
          defaultValue={defaultOptions}
          onSelect={(value) => {
            const newCacheWords = [...cacheWords, value]
            localStorage.setItem('cacheWords', JSON.stringify(newCacheWords))
          }}
          onDeselect={(value) => {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            const newCacheWords = cacheWords.filter((word: string) => word !== value)
            localStorage.setItem('cacheWords', JSON.stringify(newCacheWords))
          }}
          onSearch={(value) => {
            setOptions(
              allWords
                .filter((word) => word.indexOf(value) === 0)
                .map((word) => {
                  const w: Word = map.get(word) as Word
                  return { value: word, label: `${word} ${w.trans[0]}` }
                }),
            )
          }}
        />
      )}
      <Button onClick={handleClick}>确定</Button>
      <Button
        onClick={() => {
          localStorage.removeItem('cacheWords')
          location.reload()
        }}
      >
        清除
      </Button>
    </Row>
  )
}
